import React, { useEffect, useState } from 'react';
import { Table, Space, Button, message, Modal, Form, Input, Select, Popconfirm } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { OrganizationItem } from 'admin/schema/Cas';
import {
  getCasOrganizationsShow,
  addCasOrganization,
  updateCasOrganization,
  deleteCasOrganization,
} from 'admin/servers/modules/Cas';
import { convertToTree } from '../utils';
import { debounce, find, isEmpty } from 'lodash';
import { useSelector } from 'react-redux';
import { JSONObject } from 'admin/schema/common';

const { Option } = Select;

interface FormValues {
  name: string;
  description: string;
  pid: string;
  status: string;
  emergency: string;
}

const Organizations: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(false);
  const [data, setData] = useState<OrganizationItem[]>([]);
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [modalTitle, setModalTitle] = useState<string>('新增单位');
  const [form] = Form.useForm<FormValues>();
  const [editingOrg, setEditingOrg] = useState<OrganizationItem | null>(null);
  const loginInfo = useSelector((state: JSONObject) => state.loginInfo);
  const isAdmin = !isEmpty(
    find(loginInfo.roles, {
      code: 'CHAO_JI_GUAN_LI_YUAN',
    })
  );

  const fetchOrganizationsTree = async (page = 1, pageSize = 10) => {
    setLoading(true);
    try {
      const response = await getCasOrganizationsShow();
      if (response.status === 200) {
        setData(convertToTree(response.data));
      }
    } catch (error) {
      console.error('获取单位树出错:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchOrganizationsTree();
  }, []);

  const handleAdd = () => {
    setModalTitle('新增单位');
    setEditingOrg(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (record: OrganizationItem) => {
    setModalTitle('编辑单位');
    setEditingOrg(record);
    form.setFieldsValue({
      name: record.name,
      description: record.description || '',
      pid: record.pid,
      // status: record.status.toString(),
      emergency: record.emergency.toString(),
    });
    setModalVisible(true);
  };

  const handleDelete = async (id: string) => {
    try {
      const response = await deleteCasOrganization({ id });
      if (response.status === 200) {
        message.success('删除成功');
        fetchOrganizationsTree();
      }
    } catch (error) {
      console.error('删除出错:', error);
    }
  };

  const handleModalOk = debounce(async () => {
    try {
      const values = await form.validateFields();

      if (editingOrg) {
        // 更新
        const response = await updateCasOrganization({
          id: editingOrg.id,
          name: values.name,
          code: editingOrg.code,
          display: editingOrg.display,
          description: values.description,
          pid: values.pid,
          status: 1,
          ...(isAdmin ? { emergency: Number(values.emergency) } : {}),
        });

        if (response.status === 200) {
          message.success('更新成功');
          setModalVisible(false);
          fetchOrganizationsTree();
        }
      } else {
        // 新增
        const response = await addCasOrganization({
          name: values.name,
          description: values.description,
          pid: values.pid,
          status: 1,
          display: 1, // 默认设置为显示
          ...(isAdmin ? { emergency: Number(values.emergency) } : {}),
        });

        if (response.status === 200) {
          message.success('添加成功');
          setModalVisible(false);
          fetchOrganizationsTree();
        }
      }
    } catch (error) {
      console.error('表单验证或提交出错:', error);
    }
  }, 500);

  const handleModalCancel = () => {
    setModalVisible(false);
  };

  const columns: ColumnsType<OrganizationItem> = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      width: '350px',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      render: text => text || '-',
    },
    // {
    //   title: '状态',
    //   dataIndex: 'status',
    //   key: 'status',
    //   width: '100px',
    //   render: status => (status === 1 ? '启用' : '禁用'),
    // },
    {
      title: '创建时间',
      dataIndex: 'createdTime',
      key: 'createdTime',
      width: '200px',
      render: time => new Date(time).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      width: '180px',
      render: (_, record) => (
        <Space size="middle">
          <Button type="link" onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Popconfirm
            title="确定要删除此单位吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 构建单位树形选择器的选项
  const buildTreeOptions = (items: OrganizationItem[], level = 0) => {
    return items
      .map(item => {
        const prefix = level > 0 ? '　'.repeat(level) + '└ ' : '';
        const result = [
          <Option key={item.id} value={item.id}>
            {prefix + item.name}
          </Option>,
        ];

        if (item.children && item.children.length > 0) {
          return [...result, ...buildTreeOptions(item.children, level + 1)];
        }

        return result;
      })
      .flat();
  };

  return (
    <div style={{ padding: '24px' }}>
      <div style={{ marginBottom: '16px' }}>
        <Button type="primary" onClick={handleAdd}>
          新增单位
        </Button>
      </div>
      <Table
        columns={columns}
        dataSource={data}
        rowKey="id"
        loading={loading}
        pagination={{ pageSize: 10 }}
      />

      <Modal
        title={modalTitle}
        visible={modalVisible}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
        maskClosable={false}
        destroyOnClose
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="name"
            label="名称"
            rules={[
              { required: true, message: '请输入名称' },
              { max: 60, message: '请输入60位以内字符' },
            ]}
          >
            <Input placeholder="请输入名称" />
          </Form.Item>

          <Form.Item
            name="description"
            label="描述"
            rules={[{ max: 255, message: '请输入255位以内字符' }]}
          >
            <Input.TextArea placeholder="请输入描述" />
          </Form.Item>

          <Form.Item name="pid" label="上级单位" initialValue="0">
            <Select placeholder="请选择上级单位" disabled={!!editingOrg}>
              <Option value="0">无（顶级单位）</Option>
              {buildTreeOptions(data)}
            </Select>
          </Form.Item>

          {/* <Form.Item name="status" label="状态" initialValue="1">
            <Select>
              <Option value="1">启用</Option>
              <Option value="0">禁用</Option>
            </Select>
          </Form.Item> */}
          {isAdmin && (
            <Form.Item name="emergency" label="应急单位" initialValue="0">
              <Select>
                <Option value="0">否</Option>
                <Option value="1">是</Option>
              </Select>
            </Form.Item>
          )}
        </Form>
      </Modal>
    </div>
  );
};

export default Organizations;
